package com.sxbbc.seller.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.files.RestUploadFileInfo;
import com.sxbbc.common.basics.files.UploadUtils;
import com.sxbbc.common.basics.utils.encrypts.des.DESEncode;
import com.sxbbc.common.basics.utils.statics.FunctionUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.entity.jz.BLogin;
import com.sxbbc.common.core.entity.jz.BLogs;
import com.sxbbc.common.core.entity.jz.BMenus;
import com.sxbbc.common.core.entity.jz.BRoles;
import com.sxbbc.common.core.service.IBLoginService;
import com.sxbbc.common.core.service.IBLogsService;
import com.sxbbc.common.core.service.IBRolesService;
import com.sxbbc.common.core.utils.BasePage;
import com.sxbbc.common.core.utils.FileUtils;
import com.sxbbc.common.core.utils.MultipartFileToFile;
import com.sxbbc.seller.common.MappingUtils;
import com.sxbbc.seller.util.BusinessSession;
import com.sxbbc.seller.util.SystemLog;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author YQQ
 * 角色管理/操作员管理/系统日志
 */
@Controller
public class BaseController {
	
	
	@Autowired
	private HttpServletRequest request;
    @Autowired
    private IBLoginService bLoginService;
    @Autowired
    private IBRolesService bRolesService;
    @Autowired
    private IBLogsService bLogsService;

    /**
     * 操作员列表页面
     */
    @GetMapping(value = MappingUtils.SHOW_USER_LIST)
    public ModelAndView showUsersList(HttpServletRequest request, BasePage<BLogin> page, BLogin bLogin) {
        Integer bid = BusinessSession.getBid(request);
        bLogin.setBid(bid);
        BasePage<BLogin> userPage = bLoginService.queryList(page, bLogin);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_USER_LIST);
        view.addObject("pageInfo", userPage);
        return view;
    }

    /**
     * 新增/编辑操作员
     *
     * @param imgUrl 头像url
     */
    @SystemLog(methods = "新增编辑操作员", module = "系统管理")
    @RequestMapping(value = MappingUtils.EDIT_USER)
    @ResponseBody
    public RestResponse editUser(@RequestParam(name = "imgUrl", required = false) MultipartFile imgUrl,
                                 BLogin bLogin, HttpServletRequest request) {
        Integer bid = BusinessSession.getBid(request);
        if (bid == null) {
            return GetRest.getFail("商家登录异常，请重新登录");
        }
        bLogin.setBid(bid);
        if (bLogin.getId() == null && StringUtils.isBlank(bLogin.getLogin())) {
            return GetRest.getFail("请输入登录名");
        }
        if (StringUtils.isBlank(bLogin.getNickName())) {
            return GetRest.getFail("请输入管理员姓名");
        }
        if (StringUtils.isBlank(bLogin.getPhone())) {
            return GetRest.getFail("请输入管理员联系电话");
        }
        if (bLogin.getRoleId() == null) {
            return GetRest.getFail("请选择管理员所属角色");
        }
        /*if (bLogin.getId() == null && imgUrl == null) {
            return GetRest.getFail("请上传管理员头像");
        }*/
        if (bLogin.getId() == null) {
            BLogin login = bLoginService.selectByLogin(bLogin.getLogin());
            if (login != null) {
                return GetRest.getFail("该登录名已存在");
            }
        }
        // 头像上传
        /*RestUploadFileInfo result = UploadUtils.getInstance().uploadFile(imgUrl);
        if (result.isStatus()) {
            bLogin.setHeadurl(result.getData());
        } else if (!result.isStatus() && imgUrl != null) {
            return GetRest.getFail("图片上传失败：" + result.getDesc());
        }*/
        //商家自己新增的不设置为主账号
        bLogin.setIsPrimaryLogin(StaticUtils.STATUS_NO);
        // 保存加密后的默认密码
        bLogin.setPassWord(DESEncode.getInstance().encrypt(StaticUtils.DEFAULT_PASSWORD));
        // 新增/编辑
        boolean save = bLoginService.saveOrUpdate(bLogin);
        if (!save) {
            throw new ThrowJsonException("保存操作员失败");
        }
        return GetRest.getSuccess("保存成功");
    }

    /**
     * 新增/编辑操作员页面
     *
     * @param id 操作员id（为空时新增）
     */
    @GetMapping(value = MappingUtils.SHOW_USER_EDIT)
    public ModelAndView showUserEdit(Integer id, HttpServletRequest request) {
        Integer bid = BusinessSession.getBid(request);
        BLogin bLogin = bLoginService.getById(id);
        QueryWrapper<BRoles> wrapper = new QueryWrapper<>();
        wrapper.eq("target_id",bid);
        List<BRoles> list = bRolesService.list(wrapper);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_USER_EDIT);
        view.addObject("user", bLogin);
        view.addObject("roles", list);
        return view;
    }

    /**
     * 启用/禁用操作员
     * @param id
     * @param status
     * @author YQQ
     */
    @RequestMapping(value = MappingUtils.HANDLE_USER_STATUS)
    @ResponseBody
    @SystemLog(methods = "启用/禁用操作员",module = "系统管理")
    public RestResponse handleUserStatus(Integer id,Integer status){
        BLogin bLogin = bLoginService.getById(id);
        if (bLogin == null) {
            return GetRest.getFail("操作员信息异常，请刷新重试");
        }
        bLogin.setStatus(status);
        boolean save = bLoginService.updateById(bLogin);
        if (!save) {
            throw new ThrowJsonException("保存操作员状态异常");
        }
        return GetRest.getSuccess("操作成功");
    }

    /**
     * 删除操作员
     * @param id
     * @author YQQ
     */
    @RequestMapping(value = MappingUtils.DELETE_USER)
    @ResponseBody
    @SystemLog(methods = "删除操作员",module = "系统管理")
    public boolean deleteUser(Integer id){
        return bLoginService.removeById(id);
    }

    /**
     * 角色列表页面
     * @author YQQ
     */
    @GetMapping(value = MappingUtils.SHOW_ROLE_LIST)
    public ModelAndView showRolesList(HttpServletRequest request) {
        QueryWrapper<BRoles> wrapper = new QueryWrapper<>();
        wrapper.eq("target_id",BusinessSession.getBid(request));
        List<BRoles> list = bRolesService.list(wrapper);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_ROLE_LIST);
        view.addObject("list", list);
        return view;
    }

    /**
     * 新增/编辑角色页面
     * @param id 角色id
     * @author YQQ
     */
    @RequestMapping(value = MappingUtils.SHOW_ROLE_EDIT)
    public ModelAndView showRoleEdit(Integer id, HttpServletRequest request) {
        Integer bid = BusinessSession.getBid(request);
        BRoles role = bRolesService.getById(id);
        List<BMenus> list = bRolesService.queryMenusByRoleId(id,bid);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_ROLE_EDIT);
        view.addObject("role", role);
        view.addObject("list", list);
        view.addObject("id", id);
        return view;
    }

    /**
     * 新增/编辑商家角色
     *@author YQQ
     */
    @RequestMapping(value = MappingUtils.EDIT_ROLE)
    @ResponseBody
    @SystemLog(methods = "新增编辑商家角色", module = "系统管理")
    public RestResponse editRole(BRoles role, HttpServletRequest request) {
        Integer bid = BusinessSession.getBid(request);
        if (bid == null) {
            return GetRest.getFail("商家登录异常，请重新登录");
        }
        role.setTargetId(bid);
        if (StringUtils.isBlank(role.getName())) {
            return GetRest.getFail("请填写角色名称");
        }
        if (StringUtils.isBlank(role.getMenuIds())) {
            return GetRest.getFail("请选择菜单");
        }
        //去重复
        Set<String> menuList = new HashSet<>(Arrays.asList(role.getMenuIds().split(",")));
        String menus = StringUtils.join(menuList.toArray(), ",");
        role.setMenuIds(menus);
        boolean b = bRolesService.saveOrUpdate(role);
        if (!b) {
            throw new ThrowJsonException("保存角色信息出错");
        }
        return GetRest.getSuccess("操作成功");
    }

    /**
     * 启用/禁用角色
     * @param id 角色id
     * @param status 状态，0禁用，1启用
     * @author YQQ
     */
    @RequestMapping(value = MappingUtils.HANDLE_ROLE_STATUS)
    @ResponseBody
    @SystemLog(methods = "启用/禁用角色",module = "系统管理")
    public RestResponse handleRoleStatus(Integer id,Integer status){
        BRoles role = bRolesService.getById(id);
        if (role == null) {
            return GetRest.getFail("角色信息异常，请刷新重试");
        }
        role.setStatus(status);
        boolean save = bRolesService.updateById(role);
        if (!save) {
            throw new ThrowJsonException("更改角色状态失败");
        }
        return GetRest.getSuccess("操作成功");
    }

    /**
     * 删除角色信息
     * @param id 角色id
     * @author YQQ
     */
    @RequestMapping(value = MappingUtils.DELETE_ROLE)
    @ResponseBody
    @SystemLog(methods = "删除角色信息",module = "系统管理")
    public boolean deleteRole(Integer id){
        return bRolesService.removeById(id);
    }

    /**
     * 日志列表
     * @author YQQ
     */
    @RequestMapping(value = MappingUtils.SHOW_LOGS_LIST)
    public ModelAndView showLogsList(BasePage<BLogs> basePage, BLogs logs, HttpServletRequest request) {
        Integer bid = BusinessSession.getBid(request);
        logs.setBid(bid);
        Page<BLogs> pageInfo = bLogsService.queryLogsList(basePage, logs);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_LOGS_LIST);
        view.addObject("pageInfo", pageInfo);
        view.addObject("logs", logs);
        return view;
    }
    


    /**
     * 显示修改密码页面
     *
     * @param request
     * @author YQQ
     */
    @RequestMapping(value = MappingUtils.SHOW_UPDATE_PASSWORD)
    public ModelAndView showUpdatePassword(HttpServletRequest request) {
        Integer userId = BusinessSession.getLoginID(request);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_UPDATE_PASSWORD);
        view.addObject("id", userId);
        return view;
    }

    /**
     * 修改密码方法
     *
     * @param userId    登录的用户id
     * @param oldPwd    旧密码
     * @param newPwdOne 新密码1
     * @param newPwdTwo 新密码2
     * @return com.function.common.RestResponse
     * @author YQQ
     */
    @RequestMapping(value = MappingUtils.UPDATE_PASSWORD)
    @ResponseBody
    @SystemLog(methods = "修改登录密码", module = "用户管理")
    public RestResponse updatePassword(Integer userId, String oldPwd, HttpServletRequest request,
                                       String newPwdOne, String newPwdTwo) {
        BLogin bLogin = bLoginService.getById(userId);
        if (bLogin == null) {
            return GetRest.getFail("该用户不存在");
        }
        if (StringUtils.isBlank(oldPwd)) {
            return GetRest.getFail("请输入原密码");
        }
        if (StringUtils.isBlank(newPwdOne) || StringUtils.isBlank(newPwdTwo)) {
            return GetRest.getFail("请输入新密码");
        }
        if (newPwdOne.length() < 7 || newPwdTwo.length() < 7) {
            return GetRest.getFail("密码长度不能少于6位");
        }
        // 加密类实例
        DESEncode des = DESEncode.getInstance();
        // 原密码加密
        String oldPassword = des.encrypt(oldPwd);
        // 两次新密码加密
        String newPasswordOne = des.encrypt(newPwdOne);
        String newPasswordTwo = des.encrypt(newPwdTwo);
        if (!StringUtils.equals(oldPassword, bLogin.getPassWord())) {
            return GetRest.getFail("原密码不正确");
        }
        if (!StringUtils.equals(newPasswordOne, newPasswordTwo)) {
            return GetRest.getFail("两次输入的新密码不一致");
        }
        bLogin.setPassWord(newPasswordOne);
        boolean b = bLoginService.updateById(bLogin);
        if (!b) {
            throw new ThrowJsonException("密码修改失败");
        }
        return GetRest.getSuccess("修改成功");
    }

    /**
     * 富文本文件上传
     * @param upfile 文件
     * @author leehao
     * @return java.lang.Object
     */
    @RequestMapping(value = MappingUtils.UPLOAD_RICH_FILE)
    @ResponseBody
    public Object uploadFile(@Param("upfile") MultipartFile upfile){
        return FunctionUtils.uploadFile(upfile);
    }
    
    /**单文件上传
     * @param file
     * @return
     */
    @RequestMapping(value = MappingUtils.UPLOAD_ONE_FILE)
    @ResponseBody
    public RestUploadFileInfo uploadOneFile(@Param("file") MultipartFile file){
    	Integer bid = BusinessSession.getBid(request);
    	if(bid == null) {
    		request.getRequestDispatcher(MappingUtils.SHOW_LOGIN);
    	}
        try {
            File fe= MultipartFileToFile.multipartFileToFile(file);
            String url = FileUtils.up(fe);
            return new RestUploadFileInfo().getSuccess(url);
        }catch (Exception e){
            return new RestUploadFileInfo().getFail("图片上传失败，请重试");
        }
    }
    
}
